package cn.ug.product.web.job;

import cn.ug.account.bean.DataDictionaryBean;
import cn.ug.bean.base.SerializeObject;
import cn.ug.feign.DataDictionaryService;
import cn.ug.msg.bean.status.CommonConstants;
import cn.ug.msg.bean.type.SmsType;
import cn.ug.msg.mq.Sms;
import cn.ug.product.bean.response.ProductManageBean;
import cn.ug.product.service.ProductService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.config.QueueName.QUEUE_MSG_SMS_SEND;

@Component
public class PullOffShelvesJobs {
    private Log log = LogFactory.getLog(PullOffShelvesJobs.class);
    @Autowired
    private ProductService productService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Scheduled(fixedRate = 60 * 1000)
    public void pullOffShelvesJob() {
        List<ProductManageBean> products = productService.listOverdueProduct();
        if (products != null && products.size() > 0) {
            for (ProductManageBean product : products) {
                String[] id = {product.getId()};
                if (productService.updateShelfState(id, 2) > 0) {
                    SerializeObject<List<DataDictionaryBean>> beans = dataDictionaryService.findListByClassification(CommonConstants.MsgType.PRODUCT_DOWN_SHELF.getName(), 1);
                    if (beans != null && beans.getData() != null) {
                        List<DataDictionaryBean> data = beans.getData();
                        if (data != null && data.size() > 0) {
                            for (DataDictionaryBean bean : data) {
                                Sms sms = new Sms();
                                sms.setPhone(bean.getItemValue());
                                sms.setType(SmsType.BECOME_DUE);
                                Map<String, String> paramMap = new HashMap<>(2);
                                paramMap.put("produtName", product.getName());
                                paramMap.put("hour", String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
                                sms.setParamMap(paramMap);
                                amqpTemplate.convertAndSend(QUEUE_MSG_SMS_SEND, sms);
                            }
                        }
                    }
                }
            }
        }
    }
}
